import _ from 'lodash'
import userAgent from './userAgent.js'
import webviewJavascriptBridge from './webviewJavascriptBridge.js'
import Cookies from 'js-cookie'
import $ from 'jquery'

export default {
  getUid () {
    let q = $.Deferred()
    let uid = Cookies.get('vipbanlvUid')
    let version = Cookies.get('version')
    let uidtoken = Cookies.get('uidtoken')
    if (_.isNil(uid) || _.isNil(version) || _.isNil(uidtoken)) {
      const osType = userAgent.getOS()
      if (osType === 'ios') {
        webviewJavascriptBridge.init(bridge => {
          bridge.callHandler('vipbanlvUidCall', {}, data => {
            Cookies.set('vipbanlvUid', data.vipbanlvUid)
            Cookies.set('version', data.version)
            Cookies.set('uidtoken', data.uidtoken)
            uid = data.vipbanlvUid
            version = data.version
            uidtoken = data.uidtoken
            q.resolve({ uid, version })
          })
        })
      } else if (osType === 'android') {
        if (!_.isNil(window.vipbanlvFunc)) {
          // 调用注入的js对象的方法
          let dataForAndroid = window.vipbanlvFunc.vipbanlvUidCall()
          // json 字符串转js对象
          if (_.isString(dataForAndroid)) {
            dataForAndroid = _.attempt(JSON.parse.bind(null, dataForAndroid))
          }
          // 存cookies
          Cookies.set('vipbanlvUid', dataForAndroid.vipbanlvUid)
          Cookies.set('version', dataForAndroid.version)
          Cookies.set('uidtoken', dataForAndroid.uidtoken)
          // 设置返回值
          uid = dataForAndroid.vipbanlvUid
          version = dataForAndroid.version
          uidtoken = dataForAndroid.uidtoken

          q.resolve({ uid, version, uidtoken })
        } else {
          q.reject()
        }
      } else {
        q.reject()
      }
    } else {
      q.resolve({ uid, version, uidtoken })
    }

    return q.promise()
  }
}
